<!-- 图片裁剪 -->
<template>
  <!-- 按钮 -->
  <el-button type="primary">
    <input
      type="file"
      ref="uploadInput"
      accept="image/jpg, image/jpeg, image/png"
      @change="cuttingFile"
    />
    裁剪上传
  </el-button>

  <!-- 裁剪弹层 -->
  <el-dialog
    v-model="pData.show"
    title="裁剪图片"
    width="80%"
    :append-to-body="true"
  >
    <div>
      <vue-picture-cropper
        :boxStyle="{
          width: '100%',
          height: '100%',
          maxHeight: '60vh',
          backgroundColor: '#f8f8f8',
          margin: 'auto',
        }"
        :img="pData.pic"
        :options="options"
        :key="numKey"
      />
    </div>
    <div class="flex c1">
      <el-button @click="upKey(500 / 281)">500:281</el-button>
      <el-button @click="upKey(1 / 1)">1:1</el-button>
      <el-button @click="clearCropper">不裁剪</el-button>
      <el-button @click="pData.show = false">关闭</el-button>
      <el-button type="primary" @click="successImg()">确定</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import VuePictureCropper, { cropper } from "vue-picture-cropper";
import { ElMessage } from "element-plus";
import { post } from "@/common/http";

const emit = defineEmits<{
  (e: "img", data?: string): void; //向父组件传递 图片裁剪成功的数据
}>();

const pData = reactive({
  show: false,
  pic: "",
});

const options = ref<any>({
  viewMode: 1,
  dragMode: "crop",
  aspectRatio: 1 / 1,
});

//更新裁剪配置
const numKey = ref(1);
function upKey(data: any) {
  options.value.aspectRatio = data;
  numKey.value++;
}

//裁剪组件配置
const uploadInput = ref<HTMLInputElement>(); //获取上传裁剪图片按钮

//选择图片裁剪
const cuttingFile = (e: any) => {
  console.log(666);
  pData.pic = "";
  // 获取选取的文件
  const target = e.target;
  const { files } = target;
  if (!files) return;
  const file = files[0];

  // 转换为base64传给裁切组件
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    // emit("update:modelValue", false);

    // 更新裁切弹窗的图片源
    pData.pic = String(reader.result);
    pData.show = true;

    // 清空已选择的文件
    if (!uploadInput.value) return;
    uploadInput.value.value = "";
  };
};

//不裁剪
function clearCropper() {
  cropper!.clear();
}

//确定图片 获取裁切结果
function successImg() {
  let base64 = cropper!.getDataURL({
    fillColor: "transparent",
  });

  console.log(base64);

  //预览后台，操作提示
  ElMessage.success("裁剪获取base64数据成功，这里需要对接图片上传后台功能");

  let url = "other/verify2.jpg"; //上传成功之后返回的图片url路径

  pData.show = false;
  emit("img", url); //返回上传成功之后的图片url路径
}
</script>

<style scoped lang="scss">
.c1 {
  justify-content: flex-end;
  margin-top: 10px;
}

.c1 .a-but {
  margin-left: 20px;
}

.el-button {
  position: relative;
  margin-left: 15px;
  overflow: hidden;

  input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
    filter: alpha(opacity=0);
    cursor: pointer;
  }
}
</style>
